package Day18_网络编程.ZuoYe.Test2;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

/**
 * @author zhangyan
 * @date 2020/5/10 17:04
 */
public class Server {
    public static void main(String[] args) throws Exception {
        //**服务端2**

        //创建服务端对象,指定端口
        ServerSocket ss = new ServerSocket(8888);

        //调用accept方法,等待客户端连接
        Socket socket = ss.accept(); //连接成功返回socket对象,否则阻塞状态

        //Socket对象调用getInputStream方法获得字符缓冲输入流对象,关联连接通道
        BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));

        //Socket对象调用getOutputStream方法获得字符缓冲输出流对象,关联连接通道
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));

        //创建Scanner对象
        Scanner sc = new Scanner(System.in);

        //死循环
        while (true) {

            //读取客户端的数据
            System.out.println("客户端消息:" + br.readLine());

            //写数据
            System.out.println("输入回复给客户端的消息:");
            String massage = sc.nextLine();

            //判断输入的是否为exit
            if (massage.equals("exit")) {
                break;
            }
            //写出数据
            bw.write(massage);
            //换行
            // bw.newLine(); 相当于 socket.shutdownOutput();
            //刷新
            bw.flush();
            socket.shutdownOutput();
        }
    }
}
